import acl
import threading
import psutil
import logging
import sys
import os
from queue import Queue
from datetime import datetime
from functools import wraps
from .ConstModule import DEBUG, INFO, WARNING, ERROR, ACL_ERROR_NONE

class DemoLog():
    def __init__(self):
        self.now_time = datetime.now().strftime('%Y-%m-%d')
        self.filename = 'pyACL_Demo-'+ self.now_time+'.log'
        self.formatter = logging.Formatter('%(asctime)s-%(message)s')
        self.level = logging.DEBUG
        self.logger = logging.getLogger('demo_log')
        self.console_handler = logging.StreamHandler(sys.stdout)
        self.file_handler = logging.FileHandler(self.filename)
        self.log_config()
        #self.msg_q = Queue(maxsize=300)
        self.set_where_log_to(True, True)
    def log_config(self):
        self.console_handler.setLevel(level=self.level)
        self.console_handler.setFormatter(self.formatter)
        self.file_handler.setLevel(level=self.level)
        self.file_handler.setFormatter(self.formatter)
        self.logger.setLevel(level=self.level)

    def set_where_log_to(self, need_file: bool, need_console: bool):
        if need_console:
            self.logger.addHandler(self.console_handler) 
        if need_file:
            self.logger.addHandler(self.file_handler)

    def do_log(self, level, class_name, func_name,  message: str):
         pid = os.getpid()
         p = psutil.Process(pid)
         t = threading.currentThread()         
         p_info = '[PID:' + str(pid) + ']'
         #t_info = '[TID:' + str(t.ident) + ',' + t.getName() + ']'
         t_info = '[' + t.getName() + ']'
         func_msg = '[' + class_name + ']' + '[' + func_name + ']'
         total_message = p_info + t_info + func_msg + ':' + message
             
         if level == DEBUG:
             self.logger.debug(total_message)
         elif level == INFO:
             total_message = '[INFO]' +total_message
             self.logger.info(total_message)
         elif level == WARNING:
             total_message = '[WARNING]' +total_message
             self.logger.warning(total_message)
         elif level == ERROR:
             total_message = '[ERROR]' +total_message
             self.logger.error(total_message)
             raise Exception(total_message) 

DemoLogger = DemoLog()

def check_ret(class_name, func_name, message, ret):
    if ret != ACL_ERROR_NONE:
        ret_msg = message + '(ret '+ str(ret) + ')'
        DemoLogger.do_log(ERROR, class_name, func_name, ret_msg)



if __name__ == '__main__':
    ret = 1
    check_ret('test','test', 'error', ret)



